package vip.mtdp.asset.core.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.mtdp.asset.core.dal.dao.PostingRuleMapper;
import vip.mtdp.asset.core.dal.domain.PostingRule;
import vip.mtdp.asset.core.dto.PostingRuleDTO;
import vip.mtdp.common.constant.CommonEnum;
import vip.mtdp.common.exception.AppRTException;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Evans.wang
 * @since 2023/10/29 14:26
 **/
@Slf4j
@Service
public class PostingRuleManager {


    @Autowired
    private PostingRuleMapper postingRuleMapper;


    /**
     * 查询posting rule
     * @param bizType
     * @return
     */
    public List<PostingRuleDTO> queryByBizType(String bizType){
        List<PostingRuleDTO> postingRuleDTOList = new ArrayList<>();
        QueryWrapper<PostingRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PostingRule::getBizType, bizType).orderByAsc(PostingRule::getSeq);
        List<PostingRule> postingRuleList = postingRuleMapper.selectList(queryWrapper);
        if (postingRuleList != null && !postingRuleList.isEmpty()){
            postingRuleList.forEach(e -> {
                //数据规则校验
                if(CommonEnum.YES.getCode().equals(e.getDoubleEntry())){
                    //复试记账payer/payee expr不能同时为空
                    if (StrUtil.isBlank(e.getPayerAccountExpr()) || StrUtil.isBlank(e.getPayeeAccountExpr())){
                        throw new AppRTException("invalid posting rule data");
                    }
                }
                if (CommonEnum.NO.getCode().equals(e.getDoubleEntry())){
                    //单边记账payer/payee expr不能同时有值
                    if (StrUtil.isNotBlank(e.getPayerAccountExpr()) && StrUtil.isNotBlank(e.getPayeeAccountExpr())){
                        throw new AppRTException("invalid posting rule data");
                    }
                }
                PostingRuleDTO postingRuleDTO = new PostingRuleDTO();
                BeanUtil.copyProperties(e, postingRuleDTO);
                postingRuleDTOList.add(postingRuleDTO);
            });
        }
        return postingRuleDTOList;
    }


}
